package com.wjf.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjf.shortlink.admin.common.biz.user.UserContext;
import com.wjf.shortlink.admin.common.constant.RedisCacheConstant;
import com.wjf.shortlink.admin.common.convention.exception.ClientException;
import com.wjf.shortlink.admin.dao.entity.GroupDAO;
import com.wjf.shortlink.admin.dao.entity.GroupUniqueDAO;
import com.wjf.shortlink.admin.dao.mapper.GroupMapper;
import com.wjf.shortlink.admin.dao.mapper.GroupUniqueMapper;
import com.wjf.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.wjf.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.wjf.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.wjf.shortlink.admin.service.GroupService;
import com.wjf.shortlink.admin.toolkit.RandomGenerator;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDAO> implements GroupService {

    private RedissonClient redissonClient;
    private RBloomFilter<String> gidRegisterCachePenetrationBloomFilter;
    private GroupUniqueMapper groupUniqueMapper;

    @Value("${short-link.group.max-num:20}")
    private Integer groupMaxNum;

    @Override
    public void saveGroup(String groupName) {
        String username = UserContext.getUserName();
        if (username == null) {
            throw new ClientException("用户未知");
        }
        saveGroup(username, groupName);
    }

    @Override
    public void saveGroup(String username, String groupName) {
        RLock lock = redissonClient.getLock(String.format(RedisCacheConstant.LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
            LambdaQueryWrapper<GroupDAO> queryWrapper = new LambdaQueryWrapper<GroupDAO>()
                    .eq(GroupDAO::getUsername, username)
                    .eq(GroupDAO::getDelFlag, 0);
            List<GroupDAO> groupDAOList = baseMapper.selectList(queryWrapper);
            if (CollUtil.isNotEmpty(groupDAOList) && groupDAOList.size() >= groupMaxNum) {
                throw new ClientException(String.format("已超过最大分组数：%d", groupMaxNum));
            }
            int retryCount = 0;
            int maxRetries = 10;
            String gid = null;
            while (retryCount < maxRetries) {
                gid = saveGroupUniqueReturnGid();
                if (StrUtil.isNotEmpty(gid)) {
                    GroupDAO groupDAO = GroupDAO.builder()
                            .gid(gid)
                            .name(username)
                            .sortOrder(0)
                            .name(groupName)
                            .build();
                    baseMapper.insert(groupDAO);
                    gidRegisterCachePenetrationBloomFilter.add(gid);
                    break;
                }
                retryCount++;
            }
            if (StrUtil.isEmpty(gid)) {
                throw new ClientException("生成分组标识频繁");
            }
        } finally {
            lock.unlock();
        }
    }

    //查询用户短链接分组集合
    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDAO> queryWrapper = Wrappers.lambdaQuery(GroupDAO.class)
                .eq(GroupDAO::getDelFlag, 0)
                .eq(GroupDAO::getUsername, UserContext.getUserName())
                .orderByDesc(GroupDAO::getSortOrder, GroupDAO::getUpdateTime);
        List<GroupDAO> groupDAOList = baseMapper.selectList(queryWrapper);
        // TODO 查询分组里的短链接数量
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDAOList, ShortLinkGroupRespDTO.class);
        shortLinkGroupRespDTOList.forEach(each -> {
            // TODO 根据gid设置分组中的短链接数量
        });
        return shortLinkGroupRespDTOList;
    }

    //修改短链接分组
    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO shortLinkGroupUpdateReqDTO) {
        LambdaUpdateWrapper<GroupDAO> updateWrapper = Wrappers.lambdaUpdate(GroupDAO.class)
                .eq(GroupDAO::getUsername, UserContext.getUserName())
                .eq(GroupDAO::getDelFlag, 0)
                .eq(GroupDAO::getGid, shortLinkGroupUpdateReqDTO.getGid());
        GroupDAO groupDAO = new GroupDAO();
        groupDAO.setName(shortLinkGroupUpdateReqDTO.getName());
        baseMapper.update(groupDAO, updateWrapper);
    }

    //删除短链接分组
    public void deleteGroup(String gid) {
        LambdaUpdateWrapper<GroupDAO> updateWrapper = Wrappers.lambdaUpdate(GroupDAO.class)
                .eq(GroupDAO::getUsername, UserContext.getUserName())
                .eq(GroupDAO::getDelFlag, 0)
                .eq(GroupDAO::getGid, gid);
        GroupDAO groupDAO = new GroupDAO();
        groupDAO.setDelFlag(1);
        baseMapper.update(groupDAO, updateWrapper);
    }

    //短链接分组排序
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(each->{
            GroupDAO groupDAO = GroupDAO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();
            LambdaUpdateWrapper<GroupDAO> updateWrapper = Wrappers.lambdaUpdate(GroupDAO.class)
                    .eq(GroupDAO::getUsername, UserContext.getUserName())
                    .eq(GroupDAO::getDelFlag, 0)
                    .eq(GroupDAO::getGid, each.getGid());
            baseMapper.update(groupDAO, updateWrapper);
        });
    }

    // 保证唯一的分组gid
    private String saveGroupUniqueReturnGid() {
        String gid = RandomGenerator.generatorRandom();
        if (gidRegisterCachePenetrationBloomFilter.contains(gid)) {
            return null;
        }
        GroupUniqueDAO groupUniqueDAO = GroupUniqueDAO.builder()
                .gid(gid)
                .build();
        try {
            groupUniqueMapper.insert(groupUniqueDAO);
        } catch (DuplicateKeyException e) {
            return null;
        }
        return gid;
    }
}

